$('.overflow').niceScroll();

var upload_files = {};
var upload_files_index=0;
var template = "<div class='fileupload fileupload-new' style='float:left;margin-right:10px;'><div class='fileupload-preview thumbnail form-control'><a class='pirobox_gall img-popup' data-rel='gallery' href='IMGSRC'><img src='IMGSRC'></a></div><div style='text-align:center;'>FILENAME<i onclick='deleteInvoice(this, INDEX)' class='fa fa-times' style='margin-left:10px;font-size:15px;'></i></div></div>";
function selectFiles(){
	$("input[type='file']").click();
}
function fileChange(){
	var files = $("input[type='file']")[0].files;
	if(files==null ||files==undefined||files.length==0) return;
	for(var index in files){
		var file = files[index];
		upload_files[upload_files_index] = file;
		var fileName = files[index].name;
		var CurURL = window.URL || window.webkitURL;
		var blob = CurURL.createObjectURL(file);
		var html = template.replace(new RegExp("IMGSRC","gm"), blob).replace("FILENAME", fileName).replace("INDEX", upload_files_index);
		$("#add_invoice").before(html);
		upload_files_index++;
	}
}
function deleteInvoice(ele, index){
	var imgFileDiv = $(ele).parent().parent();
	$(imgFileDiv).remove();
	delete upload_files[index]; 
}
function uploadInvoices() {
	var period = $('#bill_date').val();
	var company_id = $('.tag-select-limited').val()[0];
	if(period == undefined || period == '') {
		$('#error_tips').html("<div class='alert alert-danger alert-dismissable fade in'>" +
                			"<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;</button>" +
                			"需选择会计期间"+
            				"</div>");
		return;
	}
	if(company_id == undefined || company_id == '') {
		$('#error_tips').html("<div class='alert alert-danger alert-dismissable fade in'>" +
    			"<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;</button>" +
    			"需选择公司名称"+
				"</div>");
		return;
	}
	if (JSON.stringify(upload_files) == JSON.stringify({})) {
		$('#error_tips').html("<div class='alert alert-danger alert-dismissable fade in'>" +
    			"<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;</button>" +
    			"需选择上传文件"+
				"</div>");
		return;
	}
	var xhr = new XMLHttpRequest();
	var form = new FormData();
	for(var index in upload_files) {
		form.append('files', upload_files[index]);
	}
	form.append('company_id', company_id);
	form.append('period', period);
	xhr.upload.addEventListener("progress", function(evt) {
		if (evt.lengthComputable) {
			var percentComplete = Math.round(evt.loaded * 100 / evt.total) / 100;
			$('.progress-bar').css('width', [percentComplete]);
		}
	}, false);
	xhr.addEventListener("abort", null, false);
	xhr.open("POST", "http://localhost:8080/ynrfinance/uploadInvoice");
	xhr.send(form);
}